#include "fileutils.h"

FileUtils::FileUtils()
{

}


QStringList FileUtils::getDirList(QString path)
{
    QDir dir(path);
    if (!dir.exists()) {
        return QStringList();
    }
    dir.setFilter(QDir::Dirs);
    // dir.setFilter(QDir::Dirs|QDir::Files);
    QStringList list = dir.entryList();
    list.removeOne(".");
    list.removeOne("..");
    return list;
}

QStringList FileUtils::getFileList(QString path)
{
    QDir dir(path);
    if (!dir.exists()) {
        return QStringList();
    }
    dir.setFilter(QDir::Files);
    QStringList list = dir.entryList();
    return list;
}

QString FileUtils::readFileToString(QString fileName)
{
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QFile::Text)) {
        QMessageBox::warning(nullptr, "Warning", "Cannot open file: " + file.errorString());
        return nullptr;
    }
    QTextStream in(&file);
    in.setCodec("UTF-8");
    QString text = in.readAll();
    file.close();
    return text;
}

void FileUtils::writeStringToFile(QString fileName, QString data)
{
    QFile file(fileName);
    if (!file.open(QFile::WriteOnly | QFile::Text)) {
        QMessageBox::warning(nullptr, "Warning", "Cannot save file: " + file.errorString());
        return;
    }
    QTextStream out(&file);
    out.setCodec("UTF-8");
    out << data;
    out.flush();
    file.close();
}

#include <QTextCodec>
QString FileUtils::GetCorrectUnicode(const QByteArray &ba) {
    QTextCodec::ConverterState state;
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    QString text = codec->toUnicode(ba.constData(), ba.size(), &state);
    if (state.invalidChars > 0) {
        text = QTextCodec::codecForName("GBK")->toUnicode(ba);
    } else {
        text = ba;
    }
    return text;
}

QString FileUtils::getFileString(QString fileName) {
    QFile f(fileName);
    QFileInfo fileInfo(fileName);
    if( !(f.exists() && fileInfo.isFile()) ){
        qDebug() <<"文件不存在";
        return nullptr;
    }
    if (!f.open(QIODevice::ReadWrite | QIODevice::Text)) {
        qDebug() <<"文件打开失败";
        return nullptr;
    }
    QByteArray textAll = f.readAll();
    f.close();
    QString text = GetCorrectUnicode(textAll);
    return text;
}
